from flask import Blueprint, render_template, request, jsonify, redirect, url_for, session

import exts
from exts import mail
from flask_mail import Message
from models import EmailCode,UserModel
from blueprints.forms import RegisterForm, LoginForm
import random
from werkzeug.security import generate_password_hash, check_password_hash

bp = Blueprint('auth', __name__, url_prefix='/auth')

@bp.route('/login',methods=['GET','POST'])
def login():
    form = LoginForm(request.form)
    user = UserModel.query.filter_by(email=form.email.data).first()
    if request.method == 'GET':
        return render_template('login.html',form=form)
    elif request.method == 'POST':
        if form.validate():
            if not user:
                print('没有该用户')
                return render_template('login.html',form=form,email_error='不存在该邮箱')
            else:
                if check_password_hash(user.password,form.password.data):
                    print('密码正确')
                    session['user_id'] = user.id
                    return redirect("/")
                else:
                    print('密码错误')
                    return render_template('login.html',form=form,password_error='密码错误')
        else:
            return render_template('login.html',form=form)



@bp.route('/register',methods=['GET','POST'])
def register():
    form = RegisterForm(request.form)
    if request.method == 'GET':
        return render_template('register.html', form=form)
    elif request.method == 'POST':
        # form = RegisterForm(request.form)
        if form.validate():
            username = form.username.data
            email = form.email.data
            password = form.password.data
            user = UserModel(username=username, email=email, password=generate_password_hash(password))
            exts.db.session.add(user)
            exts.db.session.commit()
            return redirect(url_for('auth.login'))
        else:
            print(form.errors)
            return render_template('register.html', form=form)


@bp.route('/logout')
def logout():
    session.clear()
    return redirect("/")

@bp.route('/mail/email')
def mail():
    # 2923893942@qq.com 龙
    # 3966772796@qq.com 我
    # 2119568781@qq.com 饶
    code = str(random.randint(100000, 999999))
    email=request.args.get('email')
    message=Message(subject=f'您的验证码为{code}',body=f'您的验证码为{code}',recipients=[email])
    exts.mail.send(message)
    email_code=EmailCode(email=email,code=code)
    exts.db.session.add(email_code)
    exts.db.session.commit()
    return jsonify({'code':200,'message':'成功','data':code})